import os
from flask import Flask, render_template, request, redirect, url_for, flash, session
from flask_sqlalchemy import SQLAlchemy
import matplotlib.pyplot as plt
import SparkApi
import pymysql
pymysql.install_as_MySQLdb()
from flask_cors import CORS

# 初始化Flask应用
app = Flask(__name__)
CORS(app)
# 配置MySQL数据库连接
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@localhost:3306/doubao'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 关闭修改追踪
app.config['SECRET_KEY'] = '15236'  # 设置应用的密钥
db = SQLAlchemy(app)  # 初始化数据库对象
current_dir = os.path.dirname(os.path.abspath(__file__))


#作图数据库
class imageData(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    species = db.Column(db.String(150), nullable=False)
    sepal_length = db.Column(db.Float, nullable=False)
    sepal_width = db.Column(db.Float, nullable=False)
    petal_length = db.Column(db.Float, nullable=False)
    petal_width = db.Column(db.Float, nullable=False)


# 用户模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)  # 用户ID
    username = db.Column(db.String(150), unique=True, nullable=False)  # 用户名
    password = db.Column(db.String(150), nullable=False)  # 密码

# 聊天记录模型
class ChatLog(db.Model):
    id = db.Column(db.Integer, primary_key=True)  # 聊天记录ID
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)  # 关联用户ID
    question = db.Column(db.Text, nullable=False)  # 用户提问
    answer = db.Column(db.Text, nullable=False)  # 星火的回答

# 注册路由
@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        username = request.form.get("username")  # 获取用户名
        password = request.form.get("password")  # 获取密码
        new_user = User(username=username, password=password)  # 创建新用户对象
        db.session.add(new_user)  # 添加到数据库会话
        db.session.commit()  # 提交到数据库
        flash("Registration successful!", "success")  # 注册成功提示
        return redirect(url_for("login"))  # 重定向到登录页面
    return render_template("register.html")  # 渲染注册页面

# 登录路由
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form.get("username")  # 获取用户名
        password = request.form.get("password")  # 获取密码
        user = User.query.filter_by(username=username, password=password).first()  # 查询用户
        if user:
            session['user_id'] = user.id  # 将用户ID存入会话
            session['username'] = user.username  # 将用户名存入会话
            return redirect(url_for("xin_info"))  # 登录成功，重定向到聊天界面
        else:
            flash("Login failed. Check your credentials.", "danger")  # 登录失败提示
    return render_template("login.html")  # 渲染登录页面

# 聊天界面路由
@app.route("/", methods=["GET", "POST"])
def xin_info():
    if 'user_id' not in session:
        return redirect(url_for('login'))  # 检查用户是否登录

    if request.method == "GET":
        return render_template('doubao.html')  # 渲染聊天界面
    elif request.method == "POST":
        try:
            req_dict = request.get_json()  # 获取前端发送的JSON数据
            Input = req_dict.get('input')  # 获取用户输入的问题

            # 从配置中获取API相关信息
            appid = SparkApi.config()["appid"]
            api_secret = SparkApi.config()["api_secret"]
            api_key = SparkApi.config()["api_key"]
            domain = SparkApi.config()["domain"]
            Spark_url = SparkApi.config()["Spark_url"]

            question = SparkApi.checklen(SparkApi.getText("user", Input))  # 检查问题长度
            SparkApi.answer = ""  # 清空之前的回答
            SparkApi.main(appid, api_key, api_secret, Spark_url, domain, question)  # 发送请求获取答案
            answer_txt = SparkApi.getText("assistant", SparkApi.answer)[0]["content"]  # 获取星火的回答

            # 将聊天记录保存到数据库
            chat_log = ChatLog(user_id=session['user_id'], question=Input, answer=answer_txt)
            db.session.add(chat_log)  # 添加聊天记录到数据库会话
            db.session.commit()  # 提交到数据库

            return {"msg": answer_txt}  # 返回星火的回答
        except Exception as e:
            return {"msg": str(e)}  # 返回错误信息

# 登出路由
@app.route("/logout")
def logout():
    session.pop('user_id', None)  # 从会话中移除用户ID
    session.pop('username', None)  # 从会话中移除用户名
    return redirect(url_for("login"))  # 重定向到登录页面


#绘制图片
@app.route('/generate_image_chart', methods=['GET'])
def generate_image_chart():
    image_data_list = imageData.query.all()
    species_list = []
    petal_length_list = []
    petal_width_list = []
    for data in image_data_list:
        species_list.append(data.species)
        petal_length_list.append(data.petal_length)
        petal_width_list.append(data.petal_width)

    unique_species = list(set(species_list))
    colors = ['r', 'g', 'b']
    for i, species in enumerate(unique_species):
        indices = [j for j, sp in enumerate(species_list) if sp == species]
        plt.scatter([petal_length_list[j] for j in indices], [petal_width_list[j] for j in indices],
                    c=colors[i], label=species)

    plt.xlabel('Petal Length')
    plt.ylabel('Petal Width')
    plt.title('Petal Length vs Width by Species')
    plt.legend()
    plt.savefig(os.path.join(current_dir, 'images', 'image_chart.png'))

    return {'message': 'Chart generated successfully'}
# 应用运行入口
if __name__ == '__main__':
    with app.app_context():  # 创建应用上下文
        db.create_all()  # 创建数据库表
    app.run(debug=True)  # 启动Flask应用
